﻿using System;
using System.Drawing;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace T2ReportsAssistant
{
    partial class Assistant
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static int Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            using (NotifyIcon notifyIcon = new NotifyIcon())
            {
                notifyIcon.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
                notifyIcon.BalloonTipIcon = ToolTipIcon.Info;
                notifyIcon.Text = "T2 Reports Assistant";
                notifyIcon.BalloonTipTitle = notifyIcon.Text;
                notifyIcon.Visible = true;

                if ((args.Length > 0) && String.Equals(args[0], "/setup", StringComparison.CurrentCultureIgnoreCase))
                {
                    using (SetupForm form = new SetupForm())
                    {
                        if (form.ShowDialog() == DialogResult.OK)
                        {
                            Settings.Instance.IdPassword = form.IdPassword;
                            Settings.Instance.Save();
                        }
                    }
                    return 0;
                }

                notifyIcon.BalloonTipClosed += new EventHandler(notifyIcon_BalloonTipClosed);
                notifyIcon.BalloonTipShown += (sender, e) =>
                    {
                        Timer timer = new Timer();
                        timer.Interval = 3000;
                        timer.Tick += notifyIcon_BalloonTipClosed;
                        timer.Start();
                    };

                if (Initialize())
                {
                    int rCount = ExtractAllReports();

                    Settings.Instance.Save();

                    if (rCount > 0)
                    {
                        notifyIcon.BalloonTipText = String.Format("Сохранено новых отчетов: {0}", rCount);
                        notifyIcon.ShowBalloonTip(3);

                        if (Settings.Instance.UseExternalCommand && !String.IsNullOrEmpty(Settings.Instance.ExternalCommand))
                        {
                            try
                            {
                                string[] extCmdArgs = Settings.Instance.ExternalCommand.Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                                if (extCmdArgs.Length > 0)
                                {
                                    ProcessStartInfo info = new ProcessStartInfo(extCmdArgs[0]);
                                    //info.UseShellExecute = false;
                                    //info.RedirectStandardOutput = true;
                                    info.WindowStyle = Settings.Instance.RunAsMinimized ? ProcessWindowStyle.Minimized : ProcessWindowStyle.Normal;
                                    if (extCmdArgs.Length > 1)
                                    {
                                        info.Arguments = extCmdArgs[1];
                                    }

                                    Process prc = new Process();
                                    prc.StartInfo = info;

                                    //StreamWriter outLog = new StreamWriter("output.log");

                                    prc.Start();

                                    //outLog.Write(prc.StandardOutput.ReadToEnd());
                                    //prc.WaitForExit();
                                    //outLog.Close();
                                }
                            }
                            catch (Exception e)
                            {
                                MessageBox.Show(
                                    String.Format("External command: {0}\n{1}", Settings.Instance.ExternalCommand, e.Message),
                                    "T2 Reports Assistant: Ошибка запуска внешней команды",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                            }
                        }
                        Application.Run();
                    }

                    return 0;
                }

                Settings.Instance.Save();
                return 1;
            }
        }

        static void notifyIcon_BalloonTipClosed(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}
